﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text.RegularExpressions;
using System.DirectoryServices;
using System.Configuration;
using System.Collections.Generic;

namespace RioTinto.Web.Services
{
    [ServiceContract(Namespace = "RioTinto.org")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class GALManager
    {
        [OperationContract]
        public string[] GetGALUsers(String prefixText, Int32 count)
        {
            if (String.IsNullOrEmpty(prefixText) || prefixText.Length < 3)
                return new string[] { };

            List<GALPerson> users = GALDirectory.GetPersonCollection(prefixText);

            string[] output = (from u in users
                               orderby u.CName
                               select u.CName).ToArray<String>();

            return output;
        }

    }

    public class GALServiceHostFactory : ServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            // Specify the exact URL of your web service

            Uri webServiceAddress = baseAddresses[0];
            if (baseAddresses.Length > 1)
            {
                switch (Helpers.EnvironmentState.CurrentEnvironment)
                {
                    case Helpers.CurrentEnvironment.Development:
                        webServiceAddress = new Uri(ConfigurationManager.AppSettings["ServiceHostBaseAddress.Development"]);
                        break;
                    case Helpers.CurrentEnvironment.Staging:
                        webServiceAddress = new Uri(ConfigurationManager.AppSettings["ServiceHostBaseAddress.Staging"]);
                        break;
                    case Helpers.CurrentEnvironment.Testing:
                        webServiceAddress = new Uri(ConfigurationManager.AppSettings["ServiceHostBaseAddress.Testing"]);
                        break;
                    case Helpers.CurrentEnvironment.Production:
                        webServiceAddress = new Uri(ConfigurationManager.AppSettings["ServiceHostBaseAddress.Production"]);
                        break;
                }
            }

            GALServiceHost webServiceHost = new GALServiceHost(serviceType, webServiceAddress);
            return webServiceHost;
        }
    }

    public class GALServiceHost : ServiceHost
    {
        public GALServiceHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        { }

        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();
        }
    }
}
